package com.hll.servlet;

import com.Constants;
import com.hll.model.Book;
import com.hll.model.User;
import com.hll.service.BookService;
import com.hll.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/editBook.action")
public class EditBookServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("id");
        Book book = null;

        HttpSession session = request.getSession();
        User user = (User)session.getAttribute(Constants.USER);

        /*如果是空的，说明是新建图书，那么new一本书并赋值。*/
        if(StringUtil.isEmpty(idStr)) {
            book = new Book();
        } else {
            int id = 0;
            try {
                id = Integer.parseInt(idStr);
            } catch (Exception ex) {
                session.setAttribute(Constants.ERROR_FLASH_MESSAGE, "请检查参数");
                response.sendRedirect(request.getContextPath() + "/myBook.action");
                return;
            }
            BookService bookService = new BookService();
            book = bookService.getById(id);
            if( book.getOwnerId() != user.getId()) {
                session.setAttribute(Constants.ERROR_FLASH_MESSAGE, "当前没有权限修改此书籍");
                response.sendRedirect(request.getContextPath() + "/myBook.action");
                return;
            }
        }
        request.setAttribute("book", book);
        request.getRequestDispatcher("/WEB-INF/jsp/book/edit.jsp").forward(request, response);
    }
}
